package com.studyroom.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.studyroom.common.ApiResponse;
import com.studyroom.common.Result;
import com.studyroom.entity.Order;
import com.studyroom.service.OrderService;
import com.studyroom.dto.SearchDTO;
import com.studyroom.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/orders")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @PostMapping("/search")
    public Result<IPage<Order>> search(@RequestBody SearchDTO params, 
                                      @RequestHeader("Authorization") String token) {
        String username = jwtTokenUtil.extractUsername(token.substring(7));
        
        Page<Order> page = new Page<>(params.getCurrent(), params.getSize());
        Page<Order> result = orderService.getMyOrders(username, params.getStatus(), page);
        
        return Result.success(result);
    }

    @GetMapping("/{id}")
    public Result<Order> getOrderDetail(@PathVariable Long id) {
        return Result.success(orderService.getOrderDetail(id));
    }

    @PutMapping("/{id}/status")
    public Result<Boolean> updateStatus(
            @PathVariable Long id,
            @RequestBody Map<String, Integer> params) {
        return Result.success(orderService.updateOrderStatus(id, params.get("status")));
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> deleteOrder(@PathVariable Long id) {
        try {
            orderService.deleteOrder(id);
            return ResponseEntity.ok(new ApiResponse(true, "订单删除成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new ApiResponse(false, "删除失败: " + e.getMessage()));
        }
    }
} 